package com.dms.modules.product.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.modules.product.entity.ProductComment;
import com.dms.modules.product.vo.CommentVO;
import com.dms.modules.product.vo.CommentStatisticsVO;
import com.dms.modules.merchant.vo.MerchantCommentTrendVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Result;

import java.util.List;

/**
 * 商品评论Mapper接口
 */
@Mapper
public interface ProductCommentMapper extends BaseMapper<ProductComment> {
    
    /**
     * 获取商品评论列表
     */
    @Select("SELECT c.*, u.nickname, u.avatar, p.name as productName " +
            "FROM product_comment c " +
            "LEFT JOIN user u ON c.user_id = u.id " +
            "LEFT JOIN product p ON c.product_id = p.id " +
            "WHERE c.product_id = #{productId} AND c.status = 1 AND c.deleted = 0 " +
            "ORDER BY c.create_time DESC")
    IPage<CommentVO> getProductComments(@Param("productId") Long productId, Page<CommentVO> page);
    
    /**
     * 获取用户评论列表
     */
    @Select("SELECT c.*, p.name as productName " +
            "FROM product_comment c " +
            "LEFT JOIN product p ON c.product_id = p.id " +
            "WHERE c.user_id = #{userId} AND c.deleted = 0 " +
            "ORDER BY c.create_time DESC")
    IPage<CommentVO> getUserComments(@Param("userId") Long userId, Page<CommentVO> page);
    
    /**
     * 获取评论详情
     */
    @Select("SELECT c.*, u.nickname, u.avatar " +
            "FROM product_comment c " +
            "LEFT JOIN user u ON c.user_id = u.id " +
            "WHERE c.id = #{commentId} AND c.deleted = 0")
    @Results({
        @Result(property = "images", column = "images", javaType = List.class, typeHandler = com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler.class),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "productId", column = "product_id"),
        @Result(property = "replyTime", column = "reply_time"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "isAnonymous", column = "is_anonymous"),
        @Result(property = "hasReviewed", column = "has_reviewed")
    })
    CommentVO getCommentDetail(@Param("commentId") Long commentId);
    
    /**
     * 检查是否已点赞
     */
    @Select("SELECT COUNT(*) FROM product_comment_like WHERE comment_id = #{commentId} AND user_id = #{userId} AND status = 1 AND deleted = 0")
    boolean hasLiked(@Param("commentId") Long commentId, @Param("userId") Long userId);
    
    /**
     * 添加点赞
     */
    @Update("INSERT INTO product_comment_like (comment_id, user_id, status, create_time, update_time) VALUES (#{commentId}, #{userId}, 1, NOW(), NOW())")
    int likeComment(@Param("commentId") Long commentId, @Param("userId") Long userId);
    
    /**
     * 取消点赞
     */
    @Update("UPDATE product_comment_like SET status = 0, update_time = NOW() WHERE comment_id = #{commentId} AND user_id = #{userId} AND deleted = 0")
    int unlikeComment(@Param("commentId") Long commentId, @Param("userId") Long userId);
    
    /**
     * 获取评论统计
     */
    @Select("SELECT " +
            "COUNT(*) as totalCount, " +
            "AVG(rating) as averageRating, " +
            "SUM(CASE WHEN rating >= 4 THEN 1 ELSE 0 END) as positiveCount, " +
            "SUM(CASE WHEN rating <= 2 THEN 1 ELSE 0 END) as negativeCount " +
            "FROM product_comment WHERE product_id = #{productId} AND status = 1")
    CommentStatisticsVO getCommentStatistics(@Param("productId") Long productId);

    /**
     * 获取评论列表（带条件）
     */
    @Select("<script>" +
            "SELECT * FROM product_comment " +
            "<where>" +
            "   <if test='productId != null'>AND product_id = #{productId}</if>" +
            "   <if test='userId != null'>AND user_id = #{userId}</if>" +
            "   <if test='rating != null'>AND rating = #{rating}</if>" +
            "   <if test='hasImage != null'>" +
            "       <if test='hasImage'>AND images IS NOT NULL AND images != ''</if>" +
            "       <if test='!hasImage'>AND (images IS NULL OR images = '')</if>" +
            "   </if>" +
            "</where>" +
            "ORDER BY create_time DESC" +
            "</script>")
    IPage<ProductComment> selectCommentList(Page<ProductComment> page, 
                                          @Param("productId") Long productId,
                                          @Param("userId") Long userId,
                                          @Param("rating") Integer rating,
                                          @Param("hasImage") Boolean hasImage);

    /**
     * 获取评论统计数据
     */
    @Select("SELECT " +
            "COUNT(*) as totalCount, " +
            "AVG(rating) as averageRating, " +
            "COUNT(CASE WHEN rating >= 4 THEN 1 END) as positiveCount, " +
            "COUNT(CASE WHEN rating <= 2 THEN 1 END) as negativeCount, " +
            "COUNT(CASE WHEN images IS NOT NULL AND JSON_LENGTH(images) > 0 THEN 1 END) as imageCount " +
            "FROM product_comment " +
            "WHERE product_id = #{productId} " +
            "AND deleted = 0")
    CommentStatisticsVO selectCommentStatistics(@Param("productId") Long productId);

    /**
     * 更新点赞数
     */
    @Update("UPDATE product_comment SET like_count = #{likeCount} WHERE id = #{id}")
    int updateLikeCount(@Param("id") Long id, @Param("likeCount") Integer likeCount);

    /**
     * 检查是否已评价
     */
    @Select("SELECT COUNT(*) FROM product_comment WHERE order_id = #{orderId} AND product_id = #{productId} AND has_reviewed = 1 AND deleted = 0")
    int checkHasReviewed(@Param("orderId") Long orderId, @Param("productId") Long productId);

    /**
     * 获取商品评论列表
     */
    @Select("SELECT c.*, u.nickname, u.avatar, p.name as productName " +
            "FROM product_comment c " +
            "LEFT JOIN user u ON c.user_id = u.id " +
            "LEFT JOIN product p ON c.product_id = p.id " +
            "WHERE c.product_id = #{productId} " +
            "AND c.deleted = 0 " +
            "ORDER BY c.create_time DESC")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "productId", column = "product_id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "orderId", column = "order_id"),
        @Result(property = "rating", column = "rating"),
        @Result(property = "content", column = "content"),
        @Result(property = "images", column = "images", typeHandler = com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler.class),
        @Result(property = "reply", column = "reply"),
        @Result(property = "replyTime", column = "reply_time"),
        @Result(property = "likeCount", column = "like_count"),
        @Result(property = "isAnonymous", column = "is_anonymous"),
        @Result(property = "hasReviewed", column = "has_reviewed"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "nickname", column = "nickname"),
        @Result(property = "avatar", column = "avatar"),
        @Result(property = "productName", column = "productName")
    })
    IPage<CommentVO> selectProductComments(@Param("productId") Long productId, Page<CommentVO> page);
    
    /**
     * 获取评论趋势数据
     */
    @Select("SELECT DATE(create_time) as date, " +
            "COUNT(*) as total, " +
            "COALESCE(AVG(rating), 0) as avgRating, " +
            "COUNT(CASE WHEN rating >= 4 THEN 1 END) as positiveCount, " +
            "COUNT(CASE WHEN rating <= 2 THEN 1 END) as negativeCount, " +
            "COUNT(CASE WHEN rating = 3 THEN 1 END) as neutralCount, " +
            "COUNT(CASE WHEN images IS NOT NULL AND JSON_LENGTH(images) > 0 THEN 1 END) as imageCount " +
            "FROM product_comment " +
            "WHERE product_id = #{productId} " +
            "AND create_time >= DATE_SUB(CURDATE(), INTERVAL #{days} DAY) " +
            "AND deleted = 0 " +
            "GROUP BY DATE(create_time) " +
            "ORDER BY date DESC")
    List<MerchantCommentTrendVO> selectCommentTrend(@Param("productId") Long productId, @Param("days") Integer days);

    /**
     * 获取商家所有商品的评论列表
     */
    @Select("<script>" +
            "SELECT c.*, u.nickname, u.avatar, p.name as productName " +
            "FROM product_comment c " +
            "LEFT JOIN user u ON c.user_id = u.id " +
            "LEFT JOIN product p ON c.product_id = p.id " +
            "WHERE c.product_id IN " +
            "<foreach collection='productIds' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "<if test='rating != null'> AND c.rating = #{rating}</if>" +
            "<if test='hasImage != null'>" +
            "  <if test='hasImage'> AND c.images IS NOT NULL AND JSON_LENGTH(c.images) > 0</if>" +
            "  <if test='!hasImage'> AND (c.images IS NULL OR JSON_LENGTH(c.images) = 0)</if>" +
            "</if>" +
            " AND c.deleted = 0" +
            " ORDER BY " +
            "<choose>" +
            "  <when test=\"sortField == 'rating'\">c.rating</when>" +
            "  <when test=\"sortField == 'likeCount'\">c.like_count</when>" +
            "  <otherwise>c.create_time</otherwise>" +
            "</choose>" +
            " ${sortOrder == 'asc' ? 'ASC' : 'DESC'}" +
            "</script>")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "productId", column = "product_id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "orderId", column = "order_id"),
        @Result(property = "rating", column = "rating"),
        @Result(property = "content", column = "content"),
        @Result(property = "images", column = "images", typeHandler = com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler.class),
        @Result(property = "reply", column = "reply"),
        @Result(property = "replyTime", column = "reply_time"),
        @Result(property = "likeCount", column = "like_count"),
        @Result(property = "isAnonymous", column = "is_anonymous"),
        @Result(property = "hasReviewed", column = "has_reviewed"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "updateTime", column = "update_time"),
        @Result(property = "nickname", column = "nickname"),
        @Result(property = "avatar", column = "avatar"),
        @Result(property = "productName", column = "productName")
    })
    IPage<CommentVO> selectMerchantComments(Page<CommentVO> page, 
                                           @Param("productIds") List<Long> productIds,
                                           @Param("rating") Integer rating,
                                           @Param("hasImage") Boolean hasImage,
                                           @Param("sortField") String sortField,
                                           @Param("sortOrder") String sortOrder);
} 